package cn.com.dhcc.app.pub.module.authmgr.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.annotation.CoreMenuCode;
import cn.com.dhcc.app.core.annotation.CoreMenuCode.CORE_LEAF_MENU;
import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.base.log.LogType;
import cn.com.dhcc.app.core.component.db.orm.WhereCondition;
import cn.com.dhcc.app.core.component.db.orm.valuebean.LikeValue;
import cn.com.dhcc.app.core.component.log.Log;
import cn.com.dhcc.app.core.component.pager.Pager;
import cn.com.dhcc.app.core.component.pager.PagerData;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.tag.CommonStaticCode.ENTITY_STATUS;
import cn.com.dhcc.app.core.tag.CommonStaticCode.OPERATION_TYPE;
import cn.com.dhcc.app.core.tag.CommonStaticCode.SUCCESSFAIL;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.pub.core.AppPara.UAMS;
import cn.com.dhcc.app.pub.module.authmgr.service.AuthRightMgrService;
import cn.com.dhcc.app.pub.module.authmgr.service.AuthService;
import cn.com.dhcc.app.pub.module.authmgr.vo.RoleInfoInner;
/**
 * 
 * @日期：2013-1-6下午11:05:13
 * @作者：乔兵
 * @版权所有：东华软件
 * @版本：1.0
 */
@Controller
@RequestMapping("pub/sysmgr/authmgr")
@CoreMenuCode(belongToMenu=CORE_LEAF_MENU.ROLE_MGR)
public class AuthMgrController extends BaseController{

	@Autowired
	private AuthService authService;
	@Autowired
	private AuthRightMgrService authRightMgrService;
	
	Logger logger = Log.getLogger(LogType.AUTH_MGR);
	/***
	 * 角色列表
	 * @param model
	 * @param pager
	 * @param roleName
	 * @param order
	 * @param orderName
	 * @return
	 */
	@RequestMapping("role_list")
	public String roleList(Model model,Pager pager, String roleName, String roleCode, String roleType, String orgCode, String order,String orderName){
		try{
			WhereCondition searchData=new WhereCondition();
			searchData.where1Eq1();
			searchData.andLike("role_name", LikeValue.roundLike(StrUtil.isEmpty(roleName) ? roleName : roleName.trim()));
			searchData.andLike("role_code", LikeValue.roundLike(StrUtil.isEmpty(roleCode) ? roleCode : roleCode.trim()));
			searchData.andLike("org_code", LikeValue.roundLike(StrUtil.isEmpty(orgCode) ? orgCode : orgCode.trim()));
			searchData.andEq("role_type", roleType);
			searchData.andNotEq("role_status", ENTITY_STATUS.DELETE.getCode());
			if(StrUtil.isNotBank(orderName)){
				searchData.orderBy(orderName+" "+order);
			}
			PagerData<RoleInfoInner> pagerData = authService.listRole(pager,searchData);
			model.addAttribute("roles", pagerData.getDatas());
			setTotoal(model, pagerData.getTotal());
		} catch (ServiceException e) {
			return toAlertPage(model, e.getMessage());
		}
		return "pub/sysmgr/authmgr/auth_role_list";
	}
	/**
	 * 查看角色
	 * @param model
	 * @param roleId
	 * @return
	 */
	@RequestMapping("get_role")
	public String getRole(Model model,String roleId){
		try{
			if(!StringUtils.hasText(roleId))return toAlertPage(model, "角色id不能为空");
			RoleInfoInner roleInfo = authService.getRole(roleId);
			model.addAttribute("role", roleInfo);
			model.addAttribute("rights", authRightMgrService.listRightByRoleId(roleId,OPERATION_TYPE.GET));
		} catch (ServiceException e) {
			return toAlertPage( model, "获取角色失败");
		}
		return "pub/sysmgr/authmgr/auth_role_detail";
	}
	/**
	 * 删除角色
	 * @param model
	 * @param roleId
	 * @return
	 */
	@RequestMapping("rel_del_role")
	@ResponseBody
	public Map<String, Object>  relDelRole(Model model,String roleId){
		try{
			if(!StringUtils.hasText(roleId))return jsonFailResult("操作失败，角色id不能为空！");
			 authService.deleteRole(roleId);
			 busiLog("角色管理", "删除角色", SUCCESSFAIL.SUCCESS,null);
			 return jsonSuccessResult("删除角色成功");
		} catch (NiceException e) {
			 busiLog("角色管理", "删除角色", SUCCESSFAIL.FAIL,e.getMessage());
			return jsonFailResult(e.getMessage());
		}catch (ServiceException e) {
			return jsonFailResult("删除角色失败");
		}
	}
	/**
	 * 暂停角色
	 * @param model
	 * @param roleId
	 * @return
	 */
	@RequestMapping("del_role")
	@ResponseBody
	public Map<String, Object>  delRole(Model model,String roleId){
		try{
			if(!StringUtils.hasText(roleId))return jsonFailResult("操作失败，角色id不能为空！");
			 authService.changeRoleStatus(roleId,ENTITY_STATUS.DELETE);
			 busiLog("角色管理", "删除角色", SUCCESSFAIL.SUCCESS,null);
			 if(UAMS.isSLUAMS()){
				 pushRole();
			 }
			 return jsonSuccessResult("删除角色成功");
		} catch (NiceException e) {
			 busiLog("角色管理", "删除角色", SUCCESSFAIL.FAIL,e.getMessage());
			return jsonFailResult(e.getMessage());
		}catch (ServiceException e) {
		    busiLog("角色管理", "删除角色", SUCCESSFAIL.FAIL,e.getMessage());
			return jsonFailResult("删除角色失败");
		}
	}	
	/**
	 * 角色添加-跳转
	 * @param model
	 * @return
	 */
	@RequestMapping(value="role_add")
	public String roleAdd(Model model){
		try{
			model.addAttribute("rights", authRightMgrService.listRightByRoleId(null,OPERATION_TYPE.ADD));
			return "pub/sysmgr/authmgr/auth_role_add";
		} catch (Exception e) {
			return toAlertPage(model, "获取资源失败");
		}
	}
	/**
	 * 添加角色-提交
	 * @param model
	 * @param roleInfo
	 * @param resources
	 * @param dxpUserId
	 * @param gtpUserId
	 * @return
	 * @throws NiceException 
	 */
	@RequestMapping(value="add_role",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addRole(Model model,RoleInfoInner roleInfo,String[] rightIds,String[] orgCodes,String[] orgNames) {
		
		try{
			//水资源统一用户，角色和机构没有有关系
			if(UAMS.isSZYUUMS()){
				authService.addRoleSZY(roleInfo,rightIds);
		    //水利统一用户用户，角色和机构有关系
			}else if(UAMS.isSLUAMS()){
				authService.addRoleSL(roleInfo,rightIds,orgCodes,orgNames );
				pushRole();
			//如果用户是自己维护的，采用和水资源一样的逻辑
			}else if(UAMS.isSelfUser()){
				authService.addRoleSZY(roleInfo,rightIds);
			}else{
				busiLog("角色管理", "添加角色", SUCCESSFAIL.FAIL,"添加角色失败,未知的单点登录类型，请检查配置文件");
//				return toAlertPage(model, "添加角色失败,未知的单点登录类型，请检查配置文件");
				return jsonFailResult("添加角色失败,未知的单点登录类型，请检查配置文件");
			}
			busiLog("角色管理", "添加角色", SUCCESSFAIL.SUCCESS,null);
//			return  toAlertPage( model, "添加角色成功");
			return jsonSuccessResult("添加角色成功");
		} catch (NiceException e) {
			 busiLog("角色管理", "添加角色", SUCCESSFAIL.FAIL,e.getMessage());
			 return jsonFailResult(e.getMessage());
		} catch (ServiceException e) {
			 busiLog("角色管理", "添加角色", SUCCESSFAIL.FAIL,e.getMessage());
//				return toAlertPage(model, "添加角色失败");
				return jsonFailResult("添加角色失败");
		}
	}
	@RequestMapping(value="role_update")
	public String roleUpdate(Model model, String roleId){
		try{
			RoleInfoInner roleInfo = authService.getRole(roleId);
			model.addAttribute("roleData", roleInfo);
			model.addAttribute("rights", authRightMgrService.listRightByRoleId(roleId,OPERATION_TYPE.UPDATE));
			return "pub/sysmgr/authmgr/auth_role_update";
		} catch (ServiceException e) {
			return toAlertPage(model, "获取资源失败");
		}
	}
	/**
	 * 提交修改
	 * @param model
	 * @param roleInfo
	 * @param resources
	 * @param dxpUserId
	 * @param gtpUserId
	 * @return
	 */
	@RequestMapping(value="update_role")
	@ResponseBody
	public Map<String, Object> updateRole(Model model,RoleInfoInner roleInfo,String[] rightIds){
		try{
			authService.updateRole(roleInfo,rightIds);
			busiLog("角色管理", "修改角色", SUCCESSFAIL.SUCCESS,null);
			 if(UAMS.isSLUAMS()){
				 pushRole();
			 }
//			return  toAlertPage( model, "修改角色成功");
			return jsonSuccessResult("修改角色成功");
		} catch (ServiceException e) {
			 busiLog("角色管理", "修改角色", SUCCESSFAIL.FAIL,e.getMessage());
//			return toAlertPage(model, "修改角色失败");
			return jsonFailResult("修改角色失败");
		}
	}
	/*@RequestMapping(value="get_resource_tree_data")
	@ResponseBody
	public Map<String, Object> resourceTreeData(String[] roleId){
		try{
			String rtreedata = authService.getResourceByRoleIds(roleId,false);
			 return jsonSuccessDataResult("获取角色所属权限成功", rtreedata);
		} catch (ServiceException e) {
			return jsonFailResult("获取角色所属权限失败");
		}
	}*/
	
	
	/**
	 * 暂停角色
	 * @param id
	 * @return
	 */
	@RequestMapping("disable_role")
	@ResponseBody
	public Map<String, Object>  disableRole(String roleId){
		try{
			 authService.changeRoleStatus(roleId,ENTITY_STATUS.DISABLE);
			 busiLog("角色管理", "暂停角色", SUCCESSFAIL.SUCCESS,null);
			 return jsonSuccessResult("暂停角色成功");
		} catch (NiceException e) {
			 busiLog("角色管理", "暂停角色", SUCCESSFAIL.FAIL,e.getMessage());
			return jsonFailResult(e.getMessage());
		}catch (ServiceException e) {
		    busiLog("角色管理", "暂停角色", SUCCESSFAIL.FAIL,e.getMessage());
			return jsonFailResult("暂停角色失败");
		}
	}
	/**
	 * 开启角色
	 * @param id
	 * @return
	 */
	@RequestMapping("enable_role")
	@ResponseBody
	public Map<String, Object>  enableRole( String roleId){
		try{
			 authService.changeRoleStatus(roleId,ENTITY_STATUS.ENABLE);
			 busiLog("角色管理", "开启角色", SUCCESSFAIL.SUCCESS,null);
			 return jsonSuccessResult("开启角色成功");
		} catch (NiceException e) {
			 busiLog("角色管理", "开启角色", SUCCESSFAIL.FAIL,e.getMessage());
			return jsonFailResult(e.getMessage());
		}catch (ServiceException e) {
			 busiLog("角色管理", "开启角色", SUCCESSFAIL.FAIL,e.getMessage());
			return jsonFailResult("开启角色失败");
		}
	}
	/**
	 * 角色分配部门
	 * @param roleCodes
	 * @param orgCodes
	 * @return
	 *//*
	@RequestMapping("assign_orgs_to_roles")
	@ResponseBody
	public Map<String, Object> assignOrgsToRoles(String[] roleCodes,String[] orgCodes ){
		try {
			authService.assignOrgToRole(roleCodes,orgCodes);
		} catch (ServiceException e) {
			busiLog("角色管理", "配置角色部门关系", SUCCESSFAIL.FAIL,e.getMessage());
			return jsonFailResult("配置失败");
		} catch (NiceException e) {
			busiLog("角色管理", "配置角色部门关系", SUCCESSFAIL.FAIL,e.getMessage());
			return jsonFailResult("配置失败"+e.getMessage());
		}
		return jsonSuccessResult("配置成功");
	}*/
	/**
	 * 显示单位树
	 * @param model
	 * @param httpSession
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "org_select")
	public String orgSelect(Model model, HttpSession httpSession, HttpServletRequest request,String hasSelectedOrgCodes) {
		try {
			Map<String, String> searchMap = new HashMap<String, String>();
			String iconPath = request.getContextPath() +"/static/images/icon/org_root.png";
			String org_list = null;//JsonUtil.toJson(authService.getOrgInfoNodeList(iconPath, searchMap, getCurrentUserInfo(httpSession).getAdminOrgCode(),httpSession,hasSelectedOrgCodes));
			model.addAttribute("zOrgNodes",org_list );
			return "pub/sysmgr/authmgr/org_select";
		} catch (Exception e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
	}
	/**
	 * 推送角色到统一用户管理平台
	 * @param id
	 * @return
	 */
	@RequestMapping("push_role")
	@ResponseBody
	public Map<String, Object>  pushRole(){
		return null;
		/*String msg = "";
		try {
			List<RoleInfo> smRoleInfoList = authService.listRole(null);
			List<UamsRoleInfo> roleInfoList = new ArrayList<UamsRoleInfo>();
			List<String> toRelDeleteRole = new ArrayList<String>();//已经删除的角色，并且已经推送成功，直接删除
			for (RoleInfo smRole : smRoleInfoList) {
				UamsRoleInfo roleInfo = new UamsRoleInfo();
				roleInfo.setRoleCode(smRole.getRoleCode());
				roleInfo.setRoleName(smRole.getRoleName());
				roleInfo.setRoleDesc(smRole.getRemark());
				if(smRole.getRoleType() != null){
					roleInfo.setRoleType(Integer.parseInt(smRole.getRoleType()));
				}
				roleInfo.setScode(UamsPluginPara.UAMS_CURRENT_APPCODE);
				roleInfo.setSname(UamsPluginPara.UAMS_CURRENT_APPNAME);
				roleInfo.setCcode(getUid());
				roleInfo.setCtime(smRole.getModified());
				roleInfo.setMtime(smRole.getModified());
				roleInfo.setNote(smRole.getRemark());
				roleInfo.setStatus(smRole.getRoleStatus());
				roleInfo.setTs(smRole.getModified());
				roleInfo.setOrgCode(smRole.getOrgCode());
				
				roleInfoList.add(roleInfo);
				if(ENTITY_STATUS.DELETE.getCode().equalsIgnoreCase(smRole.getRoleStatus())){
					toRelDeleteRole.add(smRole.getId());
				}
			}
			//更新本地用户信息
			UamsService service = authService.getUamsService();
			String result = service.pushRoleInfo(roleInfoList);
			String resultMsg = "推送插入"+result.split(",")[0]+"条，更新"+result.split(",")[1]+"条。";
		    busiLog("角色管理", "推送角色到统一用户管理平台", SUCCESSFAIL.SUCCESS,resultMsg);
		    for (Iterator<String> iterator = toRelDeleteRole.iterator(); iterator
					.hasNext();) {
				String roleId = (String) iterator.next();
				authService.deleteRole(roleId);
			}
			return jsonSuccessResult("推送成功,"+resultMsg);
		} catch (ServiceException e) {
			if (msg=="") {
				msg = e.getMessage() + " 推送失败。";
			}else{
				msg = msg + ",推送失败。";
			}
			busiLog("角色管理", "推送角色到统一用户管理平台", SUCCESSFAIL.FAIL,msg);
			return jsonFailResult(msg);
		} catch (Exception e) {
			busiLog("角色管理", "推送角色到统一用户管理平台", SUCCESSFAIL.FAIL,e.getMessage());
			return jsonFailResult("推送失败"+e.getMessage());
		}*/
	}
	/**
	 * 验证角色名称是否已经存在
	 * @param newValue
	 * @param oldValue
	 * @return
	 */
	@RequestMapping("check_role_code")
	@ResponseBody
	public String checkRoleCode(@RequestParam("roleCode") String newValue, @RequestParam("oldValue") String oldValue){
		try {
			if (authService.roleCodeCheck(newValue,oldValue)) {
				return FORM_CHECK_FAIL;
			} else {
				return FORM_CHECK_SUCCESS;
			}
		} catch (ServiceException e) {
			return FORM_CHECK_FAIL;
		}
	}
	/**
	 * 验证角色名称是否已经存在
	 * @param newValue
	 * @param oldValue
	 * @return
	 */
	@RequestMapping("check_role_name")
	@ResponseBody
	public String checkRoleName(@RequestParam("roleName") String newValue, @RequestParam("oldValue") String oldValue){
		try {
			if (authService.roleNameCheck(newValue,oldValue)) {
				return FORM_CHECK_FAIL;
			} else {
				return FORM_CHECK_SUCCESS;
			}
		} catch (ServiceException e) {
			return FORM_CHECK_FAIL;
		}
	}
	
}
